/*
Copyright (c) 2010, Luca Deltodesco
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions
	  and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of
	  conditions and the following disclaimer in the documentation and/or other materials provided
	  with the distribution.
    * Neither the name of the caxe project nor the names of its contributors may be used to endorse
	 or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using SUse;
import SUse;

class SUtil {
	
	public static inline function _c(s:String) return s.charCodeAt(0)
	
	public static inline function ws(c:Int) return c <= 32 || c > 126
	public static inline function nl(c:Int) return c == _c('\n') || c == _c('\r')
	public static inline function dg(c:Int) return c >= _c('0') && c <= _c('9')
	public static inline function ch(c:Int) return dg(c) || charch(c)
	public static inline function charch(c:Int) {
		return c == _c('_')
			|| (c >= _c('a') && c <= _c('z'))
			|| (c >= _c('A') && c <= _c('Z'));
	}
	
	public static inline var ws_str = " \t\n\r";
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function isword(src:String, pos:Int, num:Int) {
		if ((pos + num - 1 >= src.length)
		|| (pos > 0 && ch(src.cat(pos - 1)))
		|| (pos + num  < src.length && ch(src.cat(pos + num)))
		|| dg(src.cat(pos))
		) return false;
		else {
			var ret = true;
			while (num-->0) {
				if (!ch(src.cat(pos + num))) {
					ret = false;
					break;
				}
			}
			return ret;
		}
		
	}
	
	public static inline function skipword(src:String, pos:Integer) {
		var ret = false;
		while (pos.i < src.length && ch(src.iat(pos))) {
			ret = true;
			pos.i++;
		}
		return ret;
	}
	
	public static inline function rskipword(src:String, pos:Integer) {
		var ret = false;
		while (pos.i > 0 && ch(src.cat(pos.i-1))) {
			ret = true;
			pos.i--;
		}
		return ret;
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function remcomp(src:String) {
		var ret = new StringBuf();
		var i = 0;
		while(i<src.length) {
			if (src.cat(i) != _c('`')) ret.addChar(src.cat(i));
			if (i + 1 < src.length && src.cat(i) == _c('`') && src.cat(i + 1) == _c('`')) {
				ret.addChar(_c('`'));
				i++;
			}
			i++;
		}
		return ret.toString();
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function skipws(src:String, pos:Integer) {
		var ret = false;
		while (pos.i < src.length && ws(src.iat(pos))) {
			ret = true;
			pos.i++;
		}
		return ret;
	}
	public static inline function rskipws(src:String, pos:Integer) {
		while (pos.i > 0 && ws(src.cat(pos.i - 1))) pos.i--;
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function skipstr(src:String, pos:Integer) {
		var ret = false;
		while (pos.i < src.length) {
			if (src.iat(pos) == _c('"')) {
				var esc = false;
				ret = true;
				while (++pos.i < src.length) {
					if (src.iat(pos) == _c('\\') && !esc) { esc = true; continue; }
					if (src.iat(pos) == _c('"') && !esc) { pos.i++; break; }
					if (esc) esc = false;
				}
				continue;
			}else if (src.iat(pos) == _c('\'')) {
				var esc = false;
				ret = true;
				while (++pos.i < src.length) {
					if (src.iat(pos) == _c('\\') && !esc) { esc = true; continue; }
					if (src.iat(pos) == _c('\'') && !esc) { pos.i++; break; }
					if (esc) esc = false;
				}
				continue;
			}else break;
		}
		return ret;
	}
	
	public static inline function skipall(src:String, pos:Integer) {
		var ret = false;
		while (pos.i < src.length) {
			if (ws(src.iat(pos))) { ret = true; pos.i++; continue; }
			else if (skipstr(src, pos)) continue;
			else break;
		}
		return ret;
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function removeComments(src:String) {
		var ret = new StringBuf();
		var pos = Integer.get(0);
		while (pos.i < src.length) {
			var opos = pos.i;
			if (skipstr(src, pos)) {
				ret.addSub(src, opos, pos.i - opos);
				continue;
			}
			
			if (pos.i + 1 < src.length) {
				if (src.iat(pos) == _c('/') && src.cat(pos.i + 1) == _c('*')) {
					pos.i += 2;
					while (pos.i + 1 < src.length) {
						if (src.iat(pos) == _c('*') && src.cat(pos.i + 1) == _c('/')) {
							pos.i += 2;
							break;
						}else pos.i++;
					}
					continue;
				}else if (src.iat(pos) == _c('/') && src.cat(pos.i + 1) == _c('/')) {
					pos.i += 2;
					while (pos.i < src.length && !nl(src.iat(pos))) pos.i++;
					continue;
				}else
					ret.addChar(src.cat(pos.i++));
			}else ret.addChar(src.cat(pos.i++));
		}
		pos.free();
		return ret.toString();
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function skiprang(src:String, pos:Integer) {
		var count = 1; pos.i++;
		while (pos.i < src.length) {
			if (skipall(src, pos)) continue;
			if (src.iat(pos) == _c('(')) count++;
			else if (src.iat(pos) == _c(')')) count--;
			if (count == 0) break;
			pos.i++;
		}
	}
	public static inline function skiprbrace(src:String, pos:Integer) {
		var count = 1; pos.i++;
		while (pos.i < src.length) {
			if (skipall(src, pos)) continue;
			if (src.iat(pos) == _c('{')) count++;
			else if (src.iat(pos) == _c('}')) count--;
			if (count == 0) break;
			pos.i++;
		}
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function skipnarg(src:String, pos:Integer) {
		var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
		while (pos.i < src.length
		 && !(src.iat(pos) == _c(',') && c0 == 0 && c1 == 0 && c2 == 0 && c3 == 0)) {
			if (skipall(src, pos)) continue;
			
			var nfunc = if(pos.i>0 && src.cat(pos.i-1)==_c('-')) false else true;
			
			var c = src.iat(pos);
			if      (c == _c('<')) c0++; else if (c == _c('>') && nfunc) c0--;
			else if (c == _c('(')) c1++; else if (c == _c(')')) c1--;
			else if (c == _c('[')) c1++; else if (c == _c(']')) c1--;
			else if (c == _c('{')) c1++; else if (c == _c('}')) c1--;
			
			if (c1 == -1) break;
			pos.i++;
		}
	}
	
	public static inline function skipmac(src:String, pos:Integer) {
		var ret = false;
		while (pos.i < src.length) {
			if (skipall(src, pos)) continue;
			else if (src.iat(pos) == _c('(')) {
				ret = true;
				break;
			}else pos.i++;
		}
		return ret;
	}
	public static inline function skipnmac(src:String, pos:Integer) {
		var count = 1; pos.i += 2;
		while (pos.i < src.length) {
			if (skipall(src, pos)) continue;
			if      (src.iat(pos) == _c('(')) count++;
			else if (src.iat(pos) == _c(')')) count--;
			if (count == 0) break;
			pos.i++;
		}
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function trimws(src:String) {
		var pos = Integer.get(0);
		skipws(src, pos);
		var end = src.length;
		while (end > 0 && ws(src.cat(end - 1))) end--;
		pos.free();
		return src.substr(pos.i, end - pos.i);
	}
	
	//----------------------------------------------------------------------------------------------
	
	static public inline var npos:Int = -1;
	
	public static inline function find_first_char(src:String, c:Int, ?start:Int=0) {
		var ret = npos;
		for (i in start...src.length) {
			if (src.cat(i) == c) {
				ret = i;
				break;
			}
		}
		return ret;
	}
	public static inline function rfind_first_char(src:String, c:Int, ?start:Int = npos) {
		if (start == npos) start = src.length;
		var ret = npos;
		while (start > 0) {
			if (src.cat(start - 1) == c) {
				ret = start-1;
				break;
			}
			start--;
		}
		return ret;
	}
	
	public static inline function find_first(src:String, c:String, ?start:Int = 0) {
		var ret = npos;
		for (i in start...(src.length - c.length+1)) {
			var br = true;
			for (j in 0...c.length) {
				if (src.cat(i + j) != c.cat(j)) {
					br = false;
					break;
				}
			}
			if (br) {
				ret = i;
				break;
			}
		}
		return ret;
	}
	
	public static inline function rfind_first(src:String, c:String, ?start:Int = npos) {
		if (start == npos) start = src.length;
		if (start > src.length - c.length) start = src.length - c.length;
		
		var ret = npos;
		while (start > 0) {
			var br = true;
			for (j in 0...c.length) {
				if (src.cat(start - 1 + j) != c.cat(j)) {
					br = false;
					break;
				}
			}
			if (br) {
				ret = start-1;
				break;
			}
			start--;
		}
		return ret;
	}
	
	public static inline function find_first_any(src:String, c:String, ?start:Int = 0) {
		var ret = npos;
		for (i in start...src.length) {
			var br = false;
			for (j in 0...c.length) {
				if (src.cat(i) == c.cat(j)) {
					br = true;
					break;
				}
			}
			if (br) {
				ret = i;
				break;
			}
		}
		return ret;
	}
	
	public static inline function find_first_not_any(src:String, c:String, ?start:Int = 0) {
	    var ret = npos;
	    for (i in start...src.length) {
	        var br = false;
	        for(j in 0...c.length) {
	            if(src.cat(i) == c.cat(j)) {
	                br = true;
	                break;
	            }
	        }
	        if(!br) {
	            ret = i;
	            break;
	        }
	    }
	    return ret;
	}
	
	public static inline function rfind_first_any(src:String, c:String, ?start:Int = npos) {
		if (start == npos) start = src.length;
		
		var ret = npos;
		while (start > 0) {
			var br = false;
			for (j in 0...c.length) {
				if (src.cat(start-1) == c.cat(j)) {
					br = true;
					break;
				}
			}
			if (br) {
				ret = start-1;
				break;
			}
			start--;
		}
		return ret;
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function getargs(src:String, pos:Integer, args:Array<String>) {
		var ipos = Integer.get(pos.i + 1);
		
		skiprang(src, pos);
		var argstr = src.substr(ipos.i, pos.i - ipos.i);
		ipos.i = 0;
		var argc = 0;
	
		while (ipos.i < argstr.length) {
			var posi = ipos.i;
			skipnarg(argstr, ipos);
			argc++;
			args.push(trimws(argstr.substr(posi, ipos.i - posi)));
			ipos.i++;
		}
		if (argstr.length != 0 && argstr.cat(argstr.length - 1) == _c(',')) {
			argc++;
			args.push("");
		}
		
		return argc;
	}
	
	public static function subtex(arg:String) {
		var cur = trimws(arg);
		var ind = find_first_char(cur,_c('('));
		if (ind != npos) {
			var ret = new StringBuf();
			
			var pos = Integer.get(ind);
			var args = new Array<String>();
			var argc = getargs(cur, pos, args);
			
			ret.addSub(cur, 0, ind);
			ret.addChar(_c('_'));
			var tex = textify(args);
			ret.addSub(tex, 0, tex.length);
			pos.free();
			
			return ret.toString();
		}else
			return cur;
	}
	
	public static function textify(args:Array<String>) {
		var ret = new StringBuf();
		for (i in args) {
			var s = subtex(i);
			ret.addSub(s, 0, s.length);
			if (i != args[args.length - 1]) ret.addChar(_c('_'));
		}
		var rs = ret.toString();
		for (i in 0...rs.length) {
			if (!ch(rs.cat(i))) rs = rs.substr(0, i) + "_" + rs.substr(i + 1);
		}
		return rs;
	}
}
